<?php

namespace App\Services;

use App\Models\Tag;
use Illuminate\Support\Str;

/**
 * 标签服务类
 * 
 * 职责：
 * - 处理标签相关的业务逻辑
 * - 标签创建、更新、删除的业务规则
 * - Slug生成和唯一性验证
 */
class TagService extends BaseService
{
    /**
     * 创建或获取标签
     * 
     * @param string $name 标签名称
     * @return Tag
     */
    public function createOrGet(string $name): Tag
    {
        $slug = Str::slug($name);
        
        return Tag::firstOrCreate(
            ['slug' => $slug],
            ['name' => $name]
        );
    }

    /**
     * 批量创建或获取标签
     * 
     * @param array $tagNames 标签名称数组
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function createOrGetMany(array $tagNames)
    {
        $tags = collect();
        
        foreach ($tagNames as $name) {
            if (!empty(trim($name))) {
                $tags->push($this->createOrGet(trim($name)));
            }
        }
        
        return $tags;
    }

    /**
     * 获取标签列表
     * 
     * @param array $filters 过滤条件
     * @param int $perPage 每页数量
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getList(array $filters = [], int $perPage = 15)
    {
        $query = Tag::withCount('posts');

        // 搜索过滤
        if (!empty($filters['search'])) {
            $search = $filters['search'];
            $query->where('name', 'like', "%{$search}%");
        }

        return $query->latest()->paginate($perPage)->withQueryString();
    }

    /**
     * 获取标签下的已发布文章
     * 
     * @param Tag $tag 标签模型
     * @param array $filters 过滤条件（如搜索）
     * @param int $perPage 每页数量
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getTagPosts(Tag $tag, array $filters = [], int $perPage = 9)
    {
        $query = \App\Models\Post::published()
            ->with(['author', 'category', 'tags'])
            ->whereHas('tags', function($q) use ($tag) {
                $q->where('tags.id', $tag->id);
            });

        // 搜索过滤
        if (!empty($filters['search'])) {
            $search = $filters['search'];
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('content', 'like', "%{$search}%");
            });
        }

        return $query->latestPublished()
                     ->paginate($perPage)
                     ->withQueryString();
    }
}

